package com.mes.cloud.service;

import com.mes.cloud.exception.BaseException;
import com.mes.cloud.dao.SysCodeGeneratorDao;
import com.mes.cloud.entity.SysCodeGenerator;
import com.mes.cloud.enums.HttpStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wxm
 * @version 2019-08-08 13:41:31
 * @email xiaomin.wu1@pactera.com
 */
@Service
public class SysCodeGeneratorService {

    private SysCodeGeneratorDao sysCodeGeneratorDao;

    private IPKeyGenerator iPKeyGenerator;

    @Autowired
    public SysCodeGeneratorService(SysCodeGeneratorDao sysCodeGeneratorDao, IPKeyGenerator iPKeyGenerator) {
        this.sysCodeGeneratorDao = sysCodeGeneratorDao;
        this.iPKeyGenerator = iPKeyGenerator;
    }

    /**
     * 获取CODE,取完CODE+1
     * 使用乐观锁，最多尝试5次
     *
     * @return
     */
    public String getCode(String type) {
        //生成code
        SysCodeGenerator sysCodeGeneratorParam = new SysCodeGenerator();
        sysCodeGeneratorParam.setType(type);
        Long code = 0L;
        //尝试5层次
        int loop = 5;
        int start = 0;
        Integer version = 1;
        while (start < loop) {
            SysCodeGenerator sysCodeGenerator = sysCodeGeneratorDao.selectOne(sysCodeGeneratorParam);
            code = sysCodeGenerator.getCode();
            code = code + 1;
            version = sysCodeGenerator.getVersion();
            version = version + 1;
            //更新条件判断version == oldversion
            int count = sysCodeGeneratorDao.updateCodeVersion(sysCodeGenerator.getId(), code, sysCodeGenerator.getVersion(), version);
            //更新成功，直接跳出循环
            if (count > 0) {
                break;
            } else {
                start++;
            }
        }
        //尝试5次失败，返回异常
        if (start >= loop) {
            throw new BaseException(HttpStatusEnum.CODE_GENERATOR_FAIL.getCode(), HttpStatusEnum.CODE_GENERATOR_FAIL.getMessage());
        }
        return code.toString();
    }
}
